package com.gx.smart.building.ui.repair.fragment

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import com.blankj.utilcode.util.ToastUtils
import com.gx.smart.building.R
import com.gx.smart.building.databinding.FragmentProcessingSubmitBinding
import com.gx.smart.building.ui.common.fragment.UploadImageFragment
import com.gx.smart.building.ui.repair.AssetsActivity
import com.gx.smart.building.ui.repair.adapter.SpareAdapter
import com.gx.smart.building.ui.repair.event.DeviceMessageEvent
import com.gx.smart.building.ui.repair.model.SparePart
import com.gx.smart.building.ui.repair.model.SpareStockMessageEvent
import com.gx.smart.building.ui.repair.viewmodel.RepairViewModel
import com.huishi.gx.ib.grpc.lib.ib.app.workorder.v1.dto.WorkOrderEventFileDto
import com.huishi.gx.ib.grpc.lib.ib.app.workorder.v1.dto.WorkOrderPreAssetDto
import com.huishi.gx.ib.grpc.lib.ib.asset.spare.v1.dto.SpareDto
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class ProcessingSubmitFragment : UploadImageFragment<RepairViewModel>() {

    private lateinit var viewBinding: FragmentProcessingSubmitBinding
    private lateinit var adapter: SpareAdapter
    var spareStocks: Map<Int, SpareDto>? = null
    var positionList: Map<Int, Int>? = null
    private var assetId: String? = null
    private var assetName: String? = null

    override fun onBindLayout(): Int = R.layout.fragment_processing_submit

    override fun getToolbarTitle(): String = "处理"

    override fun onBindViewModel(): Class<RepairViewModel> = RepairViewModel::class.java
    private var workOrderEventFileDto: MutableList<WorkOrderEventFileDto.Builder> = mutableListOf()
    override fun initContentView(root: ViewGroup) {
        viewBinding = FragmentProcessingSubmitBinding.inflate(layoutInflater, root, true)
    }

    override fun initContent() {
        super.initContent()
        viewBinding.contentEdit.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable) {
                viewBinding.wordCount.text = s.length.toString() + "/200"
            }
        })

        viewBinding.save.setOnClickListener {
            save()
        }
        initAdapter1()
        viewBinding.attachmentRecyclerView.adapter = attachmentAdapter1
        adapter = SpareAdapter(requireContext(), this)
        viewBinding.recyclerView.adapter = adapter
        adapter.add(SparePart(1))
        adapter.add(SparePart(2))
        viewBinding.select.setOnClickListener {
            startActivity(Intent(requireActivity(), AssetsActivity::class.java))
        }
        registerEventBus()
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterEventBus()
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun messageEvent(event: SpareStockMessageEvent) {
        spareStocks = event.item
        positionList = event.positionList
        adapter.notifyDataSetChanged()
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    fun messageEvent(event: DeviceMessageEvent) {
        viewBinding.select.text = event.item.assetName
        assetId = event.item.id
        assetName = event.item.assetName
    }


    private fun save() {
        val suggestion = viewBinding.contentEdit.text.toString().trim()
        if (suggestion.isNullOrEmpty()) {
            ToastUtils.showLong("请填写处理意见")
            return
        }
        setImages()
        val id = requireArguments().getString("id")!!
        val assets: List<WorkOrderPreAssetDto>? = spareStocks?.map { it ->
            val num = adapter.dataList[it.key].num
            val price = it.value.price.toDouble() * 100
            WorkOrderPreAssetDto.newBuilder()
                .setTenantNo(1)
                .setNumber(num.toLong())
                .setWorkOrderId(id)
                .setAssetId(it.value.id)
                .setAssetName(it.value.spareName)
                .setAssetCode(it.value.spareCode)
                .setModelName(it.value.model)
                .setUnit(it.value.unitName)
                .setUnitPrice(price.toLong())
                .build()
        }?.toList()
        viewModel.processTask(
            id,
            suggestion,
            workOrderEventFileDto.map { it.build() },
            assetId ?: "",
            assetName ?: "",
            assets ?: listOf()
        ).observe(viewLifecycleOwner) {
            if (it) {
                findNavController().navigate(
                    R.id.action_processingSubmitFragment_to_repairResultFragment,
                    Bundle().apply {
                        putString("type", "process")
                    }
                )
            }
        }
    }

    override fun initData() {
        viewModel.uploadSuccess.observe(viewLifecycleOwner) {
            val uploadSuccess: Boolean = it.isSuccess
            val fileName: String = it.fileName
            if (uploadSuccess) {
                picList1.add(it)
            } else {
                displayFailImage1(fileName)
            }
        }
    }

    /**
     * 同步图片信息
     */
    private fun setImages() {
        uploadImageAttachment1()
        //去除删除的图片
        picList1.filter {
            attachmentAdapter1.dataList.map { item -> item.fileName }.contains(it.fileName)
        }
            .forEach { item ->
                workOrderEventFileDto.add(
                    WorkOrderEventFileDto.newBuilder()
                        .setFileName(item.fileName)
                        .setFileUrl(item.path)
                        .setFileType(1)
                )
            }
    }

    override fun uploadTask1(fileName: String, file: ByteArray) {
        viewModel.uploadImage(fileName, file)
    }
}